package com.zyj.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ImageAction extends ActionSupport {
	
	private static final long serialVersionUID = 1L;
	
	private File myFile;
	private String myFileFileName;
	private String myFileContentType;
	

	
	public String execute(){
		return "toupload";
	}
	
	
	public String upload() throws Exception{
		ServletContext ctx = ServletActionContext.getServletContext();
		String path = ctx.getRealPath("/upload/");
		
		//myFileFileName = myFileFileName.substring(myFileFileName.lastIndexOf("."));
		myFileFileName = UUID.randomUUID().toString() + myFileFileName.substring(myFileFileName.lastIndexOf("."));
		
		
		System.out.println(path);
		System.out.println(path + "/" + myFileFileName);
		
		try {
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(path + "/" + myFileFileName)));
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
			
			byte[] buffer = new byte[1024];
			int len = -1;
			while((len = bis.read(buffer)) != -1){
				bos.write(buffer, 0, len);
			}
			bos.flush();
			bos.close();
			bis.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return "success";
	}

	
	//get,set
	public File getMyFile() {
		return myFile;
	}

	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	public String getMyFileFileName() {
		return myFileFileName;
	}

	public void setMyFileFileName(String myFileFileName) {
		this.myFileFileName = myFileFileName;
	}

	public String getMyFileContentType() {
		return myFileContentType;
	}

	public void setMyFileContentType(String myFileContentType) {
		this.myFileContentType = myFileContentType;
	}
	
	
	
	
}
